import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Group, GroupDocument } from '../entities/group.entity';

@Injectable()
export class GroupsService {
  constructor(@InjectModel(Group.name) private groupModel: Model<GroupDocument>) {}

  async create(groupData: {
    name: string;
    description?: string;
    ownerId: string;
    isPublic?: boolean;
    maxMembers?: number;
  }): Promise<Group> {
    const group = new this.groupModel({
      ...groupData,
      members: [{ userId: groupData.ownerId, role: 'admin' }],
      admins: [groupData.ownerId],
    });
    return group.save();
  }

  async findAll(): Promise<Group[]> {
    return this.groupModel.find({ isDeleted: false }).exec();
  }

  async findById(id: string): Promise<Group | null> {
    return this.groupModel.findById(id).exec();
  }

  async findByUser(userId: string): Promise<Group[]> {
    return this.groupModel
      .find({
        'members.userId': userId,
        isDeleted: false,
      })
      .exec();
  }

  async addMember(groupId: string, userId: string): Promise<Group | null> {
    return this.groupModel
      .findByIdAndUpdate(
        groupId,
        { $addToSet: { members: { userId, role: 'member' } } },
        { new: true }
      )
      .exec();
  }

  async removeMember(groupId: string, userId: string): Promise<Group | null> {
    return this.groupModel
      .findByIdAndUpdate(
        groupId,
        { $pull: { members: { userId } } },
        { new: true }
      )
      .exec();
  }

  async updateGroup(groupId: string, updateData: {
    name?: string;
    description?: string;
    avatar?: string;
    announcement?: string;
  }): Promise<Group | null> {
    return this.groupModel
      .findByIdAndUpdate(groupId, updateData, { new: true })
      .exec();
  }

  async deleteGroup(groupId: string): Promise<Group | null> {
    return this.groupModel
      .findByIdAndUpdate(groupId, { isDeleted: true }, { new: true })
      .exec();
  }
}
